package com.zxp.server.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxp.server.dto.BlogForm;
import com.zxp.server.dto.BlogInfo;
import com.zxp.server.dto.RespPageBean;
import com.zxp.server.mapper.BlogMapper;
import com.zxp.server.service.IBlogService;
import com.zxp.server.util.MarkdownUtils;
import com.zxp.server.vo.Blog;
import com.zxp.server.vo.BlogTagRelations;
import com.zxp.server.vo.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 朱小皮
 * @since 2022-05-14
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private BlogTagRelationsServiceImpl blogTagRelationsService;

    /**
     * @Description 发布博客
     * @Author 朱小皮
     * @Date 2022/5/28
     */
    @Override
    @Transactional
    @CacheEvict(value = "BlogList",allEntries=true)
    public void postBlog(BlogForm blogForm) {
        Blog blog = new Blog();
        BeanUtils.copyProperties(blogForm, blog);
        blog.setFirstPicture(isImagesTrue(blogForm.getFirstPicture()));
        blogMapper.insert(blog);
        //保存博客标签关系
        Integer[] tags = blogForm.getTagValue();
        for (Integer tag:tags) {
            BlogTagRelations blogTagRelations = new BlogTagRelations();
            blogTagRelations.setBlogid(blog.getId());
            blogTagRelations.setTagid(tag);
            blogTagRelationsService.getBaseMapper().insert(blogTagRelations);
        }
    }


    /**
     * @Description 修改博客
     * @Author 朱小皮
     * @Date 2022/5/28
     */
    @Override
    @Transactional
    //@CacheEvict(value = "BlogList",allEntries=true)
    @CacheEvict(value = "BlogInfo",key = "'BlogInfo'+#blogForm.getId()")
    public void editBlog(BlogForm blogForm) {
        Blog blog = new Blog();
        BeanUtils.copyProperties(blogForm, blog);
        blogMapper.updateById(blog);
        //保存博客标签关系,先删除旧数据
        QueryWrapper<BlogTagRelations> wrapper = new QueryWrapper<>();
        wrapper.eq("blogid",blog.getId());
        blogTagRelationsService.remove(wrapper);
        Integer[] tags = blogForm.getTagValue();
        for (Integer tag:tags) {
            BlogTagRelations blogTagRelations = new BlogTagRelations();
            blogTagRelations.setBlogid(blog.getId());
            blogTagRelations.setTagid(tag);
            blogTagRelationsService.getBaseMapper().insert(blogTagRelations);
        }
    }

    /**
     * @Description 获取博客信息
     * @Author 朱小皮
     * @Date 2022/5/28
     */
    @Override
    @Cacheable(value = "BlogList",key = "'getBlogInfos'+#currentPage+#size")
    public RespPageBean getBlogInfos(Integer currentPage, Integer size,Blog blog) {
        Page<BlogInfo> blogPage = new Page<>(currentPage, size);
        IPage<BlogInfo> blogInfo = blogMapper.getBlogInfo(blogPage,blog);
        return new RespPageBean(blogInfo.getTotal(), blogInfo.getRecords());
    }


    /**
     * @Description 根据用户获取发布状态博客
     * @Author 朱小皮
     * @Date 2022/5/28
     */
    @Override
    public RespPageBean getReleaseBlogInfosByUser(Integer currentPage, Integer size, User user) {
        Page<BlogInfo> blogPage = new Page<>(currentPage, size);
        IPage<BlogInfo> blogInfo = blogMapper.getReleaseBlogInfoByUser(blogPage,user.getId());
        return new RespPageBean(blogInfo.getTotal(), blogInfo.getRecords());
    }

    /**
     * @Description 根据用户获取草稿状态博客
     * @Author 朱小皮
     * @Date 2022/5/28
     */
    @Override
    public RespPageBean getDraftBlogInfosByUser(Integer currentPage, Integer size, User user,Blog blog) {
        Page<BlogInfo> blogPage = new Page<>(currentPage, size);
        IPage<BlogInfo> blogInfo = blogMapper.getDraftBlogInfoByUser(blogPage,user.getId(),0,blog);
        RespPageBean respPageBean = new RespPageBean(blogInfo.getTotal(), blogInfo.getRecords());
        return  respPageBean;
    }

    /**
     * @Description 根据id获取博客详情（html格式内容）
     * @Author 朱小皮
     * @Date 2022/5/28
     */
    @Override
    @Cacheable(value = "BlogInfo",key = "'BlogInfo'+#blogId")
    public BlogInfo getBlogInfoById(Integer blogId) {
        BlogInfo blogInfo = blogMapper.getBlogInfoById(blogId);
        String content = blogInfo.getContent();
        if (content != null) {
            // 将博客对象中的正文内容markdown格式的文本转换成html元素格式
            blogInfo.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        }
        return blogInfo;
    }

    /**
     * @param blogInfo
     * @Description 增加浏览量 （+1）
     * @Author 朱小皮
     * @Date 2022/5/28
     */
    @Override
    @CachePut(value = "BlogInfo",key = "'BlogInfo'+#blogInfo.getId()")
    public BlogInfo addView(BlogInfo blogInfo) {
        blogInfo.setViews(blogInfo.getViews() + 1);
        this.updateById(blogInfo);
        return blogInfo;
    }


    /**
     * @param blogId
     * @param userId
     * @Description 根据id删除博客
     * @Author 朱小皮
     * @Date 2022/5/28
     */
    @Override
    @CacheEvict(value = "BlogInfo",key = "'BlogInfo'+#blogId")
    public void deleteBlogById(Integer blogId, Integer userId) {
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        wrapper.eq("id",blogId);
        wrapper.eq("uid",userId);
        this.getBaseMapper().delete(wrapper);
    }

    /**
     * 用户提供的图片链接无效就自动生成图片
     * @param postUrl
     * @return
     */
    public String isImagesTrue(String postUrl) {
        int max = 1000;
        int min = 1;
        String picUrl = "https://unsplash.it/800/450?image=";
        try {
            URL url = new URL(postUrl);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setRequestMethod("POST");
            urlCon.setRequestProperty("Content-type",
                    "application/x-www-form-urlencoded");
            if (urlCon.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return postUrl;
            } else {
                Random random = new Random();
                int s = random.nextInt(max) % (max - min + 1) + min;
                return picUrl+s;
            }
        } catch (Exception e) {   // 代表图片链接无效
            Random random = new Random();
            int s = random.nextInt(max) % (max - min + 1) + min;
            return picUrl+s;
        }
    }
}
